package com.changhai.diabetes.service.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;

import com.changhai.diabetes.model.Patient;
import com.changhai.diabetes.model.SessionUser;
import com.changhai.diabetes.model.TableForPatient;
import com.changhai.diabetes.model.User;
import com.changhai.diabetes.service.BaseService;
import com.changhai.diabetes.service.CommonService;
import com.changhai.diabetes.util.Constants;
import com.opensymphony.xwork2.ActionContext;

/**
 * 
 * @author Andy
 * 
 */
public class CommonServiceImpl extends BaseService implements CommonService {

	public void updateSession(String dsName, Long userId, int adminType) {
		Map<String, Number> map = new HashMap<String, Number>();
		if (adminType == 0) {
			map.put("userId", userId);
		}

		List<Long> patientIds = this.getList(dsName, "interPatientUser.getByUserId", map); // 获取属于该医院的患者编号
		List<Patient> patients = new ArrayList<Patient>();
		if (patientIds != null && patientIds.size() > 0) {
			patients = this.getList(dsName, "patient.getByPatientIds", patientIds); // 获取属于该医院的患者信息
		}

		ActionContext.getContext().getSession().put(Constants.SESSION_PATIENT_IDS, patientIds);
		ActionContext.getContext().getSession().put(Constants.SESSION_PATIENT, patients);
	}

	public User auth(String dsName, String userName, String userPassword) {
		User user = new User();
		user.setUsername(userName);
		user.setUserpassword(userPassword);
		return (User) getObject(dsName, "user.getByLoginPasswd", user);
	}

	public Object getObject(String dsName, String strSQL, Object obj) {
		if (obj != null)
			return this.getDao(dsName).queryForObject(strSQL, obj);
		else
			return this.getDao(dsName).queryForObject(strSQL);
	}

	public List getList(String dsName, String strSQL, Object obj) {
		if (obj != null)
			return this.getDao(dsName).queryForList(strSQL, obj);
		else
			return this.getDao(dsName).queryForList(strSQL);
	}

	public void insertObject(String dsName, String insertSQL, Object obj) {
		if (obj != null)
			this.getDao(dsName).insert(insertSQL, obj);
		else
			this.getDao(dsName).insert(insertSQL);
	}

	public Integer insertObjectID(String dsName, String insertSQL, Object obj) {
		Integer insertid = 0;
		if (obj != null)
			insertid = this.getDao(dsName).insert(insertSQL, obj);
		return insertid;
	}

	public void updateObject(String dsName, String updateSQL, Object obj) {
		if (obj != null)
			this.getDao(dsName).update(updateSQL, obj);
		else
			this.getDao(dsName).update(updateSQL);
	}

	public void deleteObject(String dsName, String deleteSQL, Object obj) {

		if (obj != null)
			this.getDao(dsName).delete(deleteSQL, obj);
		else
			this.getDao(dsName).delete(deleteSQL);
	}

	public Integer getRowCount(String dsName, String strSQL, Object obj) {
		List list = getList(dsName, strSQL, obj);
		if (list == null || list.size() == 0)
			return 0;
		else
			return list.size();
	}

	public void uniteOld2New(String dsName, List<Object> listObj, Object obj) {

	}

	public void setNewObject(String dsName, Object obj1, Object obj2) {
	}

	@Override
	public User auth(String login, String passwd) {
		return auth(null, login, passwd);
	}

	@Override
	public void deleteObject(String deleteSQL, Object obj) {
		deleteObject(null, deleteSQL, obj);
	}

	@Override
	public List getList(String strSQL, Object obj) {
		return getList(null, strSQL, obj);
	}

	@Override
	public Object getObject(String strSQL, Object obj) {
		return getObject(null, strSQL, obj);
	}

	@Override
	public void insertObject(String insertSQL, Object obj) {
		insertObject(null, insertSQL, obj);
	}

	@Override
	public Integer insertObjectID(String insertSQL, Object obj) {
		return insertObjectID(null, insertSQL, obj);
	}

	@Override
	public void updateObject(String updateSQL, Object obj) {
		updateObject(null, updateSQL, obj);
	}

	public List<TableForPatient> getTableByPatientId(Long patientId, Integer flag) {
		List<TableForPatient> list = new ArrayList<TableForPatient>();
		if (flag == 1) {
			list = this.getBasicTables();
		} else {
			if (flag == 0) {
				if (isFirstTimeEnter(patientId)) {
					list = this.getBasicTables();
				}
			}

			Long groupid = 0L;
			if (patientId != null && patientId > 0) {
				groupid = (Long) this.getObject(Constants.DS_CHANGHAI, "interPatientGroup.getGroupIdByPatientId",
						patientId);
			}
			if (groupid != null && groupid > 0) {
				String content = (String) this.getObject(Constants.DS_CHANGHAI, "researchGroup.getContentByGroupId",
						groupid);
				if (content != null && !content.equals("")) {
					String[] ids = content.split(",");
					if (ids != null && ids.length > 0) {
						for (int i = 0; i < ids.length; i++) {
							Object ob = this
									.getObject(Constants.DS_CHANGHAI, "tableForPatient.getByPrimaryKey", ids[i]);
							if (ob != null && ob instanceof TableForPatient) {
								list.add((TableForPatient) ob);
							}
						}
					}
				}
			}
			
			for(TableForPatient tfp : list){
				String str=tfp.getTbEnName()+".getByPatientId";
				System.out.println(str);
				List tlist=this.getList(Constants.DS_CHANGHAI, str, patientId);
				if(tlist.size()>0){
					tfp.setExist(true);
				}else{
					tfp.setExist(false);
				}
			}
		}
		return list;
	}

	public List<TableForPatient> getBasicTables() {
		List<TableForPatient> list = new ArrayList<TableForPatient>();
		list = this.getList(Constants.DS_CHANGHAI, "tableForPatient.getBasicTables", Constants.BASIC_TABLE_FLAG);
		return list;
	}

	private boolean isFirstTimeEnter(Long patientId) {
		Object o = this.getObject(Constants.DS_CHANGHAI, "bear.getSeqIdByPatientId", patientId);
		if (o == null) {
			return true;
		}
		o = this.getObject(Constants.DS_CHANGHAI, "personal.getSeqIdByPatientId", patientId);
		if (o == null) {
			return true;
		}
		o = this.getObject(Constants.DS_CHANGHAI, "family.getSeqIdByPatientId", patientId);
		if (o == null) {
			return true;
		}
		return false;
	}

	public void writeLogToFile(String method, String item, Long patientid) throws IOException {
		SessionUser sUser = (SessionUser) ActionContext.getContext().getSession().get(Constants.SESSION_USER_KEY);
		PrintWriter printWriter = null;
		String filename = "d:/syslog.txt";
		String dir = filename.substring(0, filename.lastIndexOf("/") - 1);
		String record = "";

		DateFormat df = DateFormat.getDateTimeInstance();
		String operTime = df.format(new Date());
		if (sUser != null) {
			record = "用户id:" + sUser.getId() + "; 用户姓名:" + sUser.getLoginName() + "; 操作时间: " + operTime + "; 操作"
					+ method + "; 操作项:"+ item + "; 患者编号：" + patientid;
		}

		try {
			File fDir = new File(dir);
			if (!fDir.exists()) {
				FileUtils.forceMkdir(fDir);
			}
			printWriter = new PrintWriter(new FileWriter(filename, true));
			printWriter.println(record);
			printWriter.flush();
			printWriter.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != printWriter) {
				printWriter.close();
			}
		}
	}
}
